-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.


local lu = require 'luaunit'
local subcomp = require 'mcu.upgrade.sub_component'
local mdb = require 'mc.mdb'
local g_reg_param = {}

TestMcuUpgrade = {}

local function stub_mcu_subcomp_info(software_id)
    mdb.get_object = function()
        local obj = {}
        obj.Add = function(_, _, param, _, _, _)
            g_reg_param = param
        end
        return obj
    end
    subcomp.RefMcu = {}
    subcomp.Type = 0
    subcomp.No = 100
    subcomp.Index = 1
    subcomp.RefMcu.SoftwareId = software_id
    subcomp.RefMcu.get_firmeware_info = function ()
        return {
            vendor = 1,
            sku = 1,
            delay = 10
        }
    end
end

-- 测试注册固件信息里SoftwareId为有效值
function TestMcuUpgrade:test_register_mcu_software_id_val()
    local stub_software_id = 6
    stub_mcu_subcomp_info(stub_software_id)
    local ok = pcall(function()
        return subcomp:register_component_firmware_info(bus)
    end)

    lu.assertEquals(ok, true)
    lu.assertEquals(g_reg_param.Id, 'MCU_100')
    lu.assertEquals(g_reg_param.SoftwareId, stub_software_id)
end

-- 测试注册固件信息里SoftwareId为nil
function TestMcuUpgrade:test_register_mcu_software_id_nil()
    local stub_software_id = nil
    stub_mcu_subcomp_info(stub_software_id)
    local ok = pcall(function()
        return subcomp:register_component_firmware_info(bus)
    end)

    lu.assertEquals(ok, true)
    lu.assertEquals(g_reg_param.Id, 'MCU_100')
    lu.assertEquals(g_reg_param.SoftwareId, "")
end

-- 测试获取mcu详细信息
function TestMcuUpgrade:test_update_detail_info()
    local ok = pcall(function()
        return subcomp:update_detail_info()
    end)

    lu.assertEquals(ok, true)
    lu.assertEquals(subcomp.Vendor, 1)
    lu.assertEquals(subcomp.SKU, 1)
    lu.assertEquals(subcomp.Delay, 10)
end

-- 测试初始化子固件属性
function TestMcuUpgrade:test_init_subcomponent_info()
    local detail = {
        type = 3,
        no = 2,
        vendor = 5,
        sku = 3,
        major_version = 3,
        minor_version = 4,
        revision = 5,
        delay = 7
    }
    local component = subcomp.new(3, detail)
    lu.assertEquals(component.Type, detail.type)
    lu.assertEquals(component.No, detail.no)
    lu.assertEquals(component.Vendor, detail.vendor)
    lu.assertEquals(component.SKU, detail.sku)
    lu.assertEquals(component.MajorVersion, detail.major_version)
    lu.assertEquals(component.Revision, detail.revision)
end